package edu.gxnu.cetcdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.gxnu.cetcdemo.mapper.RoomMapper;
import edu.gxnu.cetcdemo.pojo.Room;
import edu.gxnu.cetcdemo.service.RoomService;
import edu.gxnu.cetcdemo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author Uplifted
* @description 针对表【room】的数据库操作Service实现
* @createDate 2024-04-02 15:09:11
*/
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room>
    implements RoomService{

    @Autowired
    private RoomMapper roomMapper;
    @Override
    public Result add(Room room) {
        try {
            if (this.save(room))
                return new Result().build(200,"机房添加成功！", null);
            else
                return new Result().build(500,"机房添加失败！", null);
        } catch (Exception e){
            if (e.getCause().getMessage().startsWith("Duplicate")) {
                return new Result().build(400, "该条记录已存在！", null);
            }

            if (e.getCause().getMessage().startsWith("Cannot add or update a child row: a foreign key constraint fails")) {
                return new Result().build(400, "用户或机房不存在！", null);
            }
            return new Result<>().build(400,e.getMessage(),null);
        }
    }

    @Override
    public Result change(Room room) {
        try{
            roomMapper.updateById(room);
            return new Result<>().build(200,"修改成功",null);
        } catch (Exception e){
            System.out.println(e.getMessage());
            return new Result().build(400,"修改失败",null);
        }

    }

    @Override
    public Result get() {
        try{
            List<Room> list = roomMapper.selectList(null);
            return new Result<>().build(200,"查询机房成功！",list);
        } catch (Exception e){
            System.out.println(e.getMessage());
            return new Result().build(400,"查询机房失败！",null);
        }
    }

    @Override
    public Result delete(Integer id) {
        try{
            roomMapper.deleteById(id);
            return new Result().build(200,"删除成功！",null);
        } catch (Exception e){
            System.out.println(e.getMessage());
            return new Result().build(400,"删除失败！",null);
        }
    }

    @Override
    public Result getRoomName() {
        LambdaQueryWrapper<Room> roomLQW = new LambdaQueryWrapper<>();
        roomLQW.select(Room::getRoomName).orderByAsc(Room::getRoomName);
        List<Room> roomList = roomMapper.selectList(roomLQW);
        List<String> list = new ArrayList<String>();
        for (Room item : roomList){
            list.add(item.getRoomName());
        }
        return new Result().build(200,"查询成功", list);
    }
}




